/**
 * 支付管理器
 * 统一管理不同支付方式和平台的支付逻辑
 */
import { AlipayService } from "./alipay.js"
import { uni } from "some-uni-library" // 假设这是uni变量的来源

export class PaymentManager {
  constructor() {
    this.alipayService = new AlipayService()
    this.paymentMethods = {
      ALIPAY: "alipay",
      WECHAT: "wechat",
      UNIONPAY: "unionpay",
    }
  }

  // 发起支付
  async pay(paymentData) {
    const { method, orderData, amount, orderNo } = paymentData

    try {
      switch (method) {
        case this.paymentMethods.ALIPAY:
          return await this.handleAlipayPayment(orderData, amount, orderNo)
        case this.paymentMethods.WECHAT:
          return await this.handleWechatPayment(orderData, amount, orderNo)
        case this.paymentMethods.UNIONPAY:
          return await this.handleUnionPayment(orderData, amount, orderNo)
        default:
          throw new Error("不支持的支付方式")
      }
    } catch (error) {
      console.error("支付失败:", error)
      throw error
    }
  }

  // 处理支付宝支付
  async handleAlipayPayment(orderData, amount, orderNo) {
    const platform = this.getCurrentPlatform()

    switch (platform) {
      case "app":
        return await this.handleAppAlipayPayment(orderData)
      case "h5":
        return await this.handleH5AlipayPayment(orderData)
      case "mp-weixin":
        return await this.handleMpAlipayPayment(orderData)
      default:
        throw new Error("当前平台不支持支付宝支付")
    }
  }

  // App环境支付宝支付
  async handleAppAlipayPayment(orderData) {
    try {
      // 首先尝试原生支付宝支付
      const isAlipayInstalled = await this.alipayService.checkAlipayInstalled()

      if (isAlipayInstalled) {
        console.log("使用原生支付宝支付")
        return await this.alipayService.pay(orderData)
      } else {
        console.log("支付宝未安装，使用WebView支付")
        return await this.alipayService.payWithWebView(orderData, {
          title: "支付宝支付",
          showToolbar: true,
          onSuccess: (result) => {
            console.log("WebView支付成功:", result)
          },
          onCancel: () => {
            console.log("用户取消支付")
          },
          onError: (error) => {
            console.error("WebView支付失败:", error)
          },
        })
      }
    } catch (error) {
      console.error("App支付宝支付失败:", error)
      throw error
    }
  }

  // H5环境支付宝支付
  async handleH5AlipayPayment(orderData) {
    try {
      this.alipayService.payInH5(orderData)
      return { success: true, message: "已打开支付页面" }
    } catch (error) {
      console.error("H5支付宝支付失败:", error)
      throw error
    }
  }

  // 小程序环境支付宝支付
  async handleMpAlipayPayment(orderData) {
    try {
      this.alipayService.payInMiniProgram(orderData)
      return { success: true, message: "支付链接已复制" }
    } catch (error) {
      console.error("小程序支付宝支付失败:", error)
      throw error
    }
  }

  // 处理微信支付
  async handleWechatPayment(orderData, amount, orderNo) {
    // 微信支付逻辑
    console.log("处理微信支付")
    // TODO: 实现微信支付逻辑
  }

  // 处理银联支付
  async handleUnionPayment(orderData, amount, orderNo) {
    // 银联支付逻辑
    console.log("处理银联支付")
    // TODO: 实现银联支付逻辑
  }

  // 获取当前平台
  getCurrentPlatform() {
    // #ifdef APP-PLUS
    return "app"
    // #endif

    // #ifdef H5
    return "h5"
    // #endif

    // #ifdef MP-WEIXIN
    return "mp-weixin"
    // #endif

    return "unknown"
  }

  // 检查支付状态
  async checkPaymentStatus(orderNo) {
    try {
      const response = await uni.request({
        url: `/api/orders/payment-status/${orderNo}`,
        method: "GET",
      })

      return response.data
    } catch (error) {
      console.error("检查支付状态失败:", error)
      throw error
    }
  }

  // 支付结果处理
  handlePaymentResult(result, orderNo) {
    const { resultStatus, result: payResult } = result

    switch (resultStatus) {
      case "9000":
        // 支付成功
        this.onPaymentSuccess(orderNo)
        break
      case "8000":
        // 正在处理中
        this.onPaymentProcessing(orderNo)
        break
      case "4000":
        // 订单支付失败
        this.onPaymentFailed(orderNo, "订单支付失败")
        break
      case "5000":
        // 重复请求
        this.onPaymentFailed(orderNo, "重复请求")
        break
      case "6001":
        // 用户中途取消
        this.onPaymentCancelled(orderNo)
        break
      case "6002":
        // 网络连接出错
        this.onPaymentFailed(orderNo, "网络连接出错")
        break
      default:
        this.onPaymentFailed(orderNo, "未知错误")
    }
  }

  // 支付成功处理
  onPaymentSuccess(orderNo) {
    uni.showToast({
      title: "支付成功",
      icon: "success",
    })

    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${orderNo}`,
      })
    }, 1500)
  }

  // 支付处理中
  onPaymentProcessing(orderNo) {
    uni.showToast({
      title: "支付处理中",
      icon: "loading",
    })

    // 可以设置定时器检查支付状态
    setTimeout(() => {
      this.checkPaymentStatus(orderNo)
    }, 3000)
  }

  // 支付失败处理
  onPaymentFailed(orderNo, message) {
    uni.showToast({
      title: message || "支付失败",
      icon: "none",
    })
  }

  // 支付取消处理
  onPaymentCancelled(orderNo) {
    uni.showToast({
      title: "支付已取消",
      icon: "none",
    })
  }
}

// 导出单例
export const paymentManager = new PaymentManager()
